/**
 * @file 工单修改-公共
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer', 'list_modify_operation', 'zmnUtils','$http'], function (exports) {

    var $ = layui.$;
    var operationUtils = layui.list_modify_operation;
    var config = layui.oms_work_config;
    var zmnUtils = layui.zmnUtils;
    var $http = layui.$http;
    var MODULE_ID_YEYX = 590;
    var MODULE_ID_SAAS = 572;
    var MODULE_ID_CNHB = 574;
    var MODULE_ID_ZS = 510;

    /**
     * 乘法函数，用来得到精确的乘法结果
     * @param {Object} arg1
     * @param {Object} arg2
     */
    function accMul(arg1, arg2) {
        var m = 0;
        m += deal(arg1);
        m += deal(arg2);
        var r1 = Number(arg1.toString().replace(".", ""));
        var r2 = Number(arg2.toString().replace(".", ""));
        return (r1 * r2) / Math.pow(10, m)
    }

    /**
     * 加法函数，用来得到精确的加法结果
     * @param {Object} arg1
     * @param {Object} arg2
     */
    function accAdd(arg1, arg2) {
        var r1 = deal(arg1);
        var r2 = deal(arg2);
        var m = Math.pow(10, Math.max(r1, r2))
        return(arg1 * m + arg2 * m) / m
    }

    /**
     * 求小数点后的数据长度
     */
    function deal(arg) {
        var t = 0;
        try {
            t = arg.toString().split(".")[1].length
        } catch(e) {}
        return t;
    }

    /**
     * 获取窗口索引
     * @returns {number} 窗口索引
     */
    function getLayerIndex () {
        return parent.layer.getFrameIndex(window.name);
    }

    /**
     * 更新弹框标题
     * @param {string} title 标题
     */
    function updateLayerTitile (title) {
        var index = getLayerIndex();
        parent.layui.$('#layui-layer' + index).find('.layui-layer-title').text(title);
    }

    /**
     * 回到操作主页面
     */
    function goOperateHome () {
        var params = zmnUtils.getQueryParams();
        _goSomeOperateHome(params);
    }

    function _goSomeOperateHome (params) {
        window.location.href = zmnUtils.serializeURL(config.url.homeURL, {
            orderId: params.orderId,
            workId: params.workId,
            operateId: config.operareIdEnum.detail,
            moduleId: params.moduleId
        });
    }

    /**
     * 创建操作列表字符串
     * @param {array} data 数据
     * @returns {string} 操作列表字符串
     */
    function createOperationPanelHtml (data) {
        var htmlStr = '';

        $.each(data, function (index, item) {
            var classArr = ['layui-btn', 'layui-btn-primary', 'layui-btn-sm'];
            // if (item.canOperate === true) {
            if (false) {
                classArr.push('layui-btn-disabled');
            }

            htmlStr += '<button class="' + classArr.join(' ') +
                '" data-url="' + item.url + '" data-id="' + item.id + '">' + item.name +'</button>'
        });

        return htmlStr;
    }

    function _findIndexOfWorkListByWorkId () {
        if (!window.workList) {
            return -1;
        }

        return window.workList.findIndex((work) => work.workId === window.workId);
    }

    function _getPrevNextButtonWrapper () {
        return $('.work-operation-header .header-left');
    }
    /**
     * 初始化操作列表按钮状态
     */
    function initPrevNextButtonStatus () {
        function _enabledBtn ($btn) {
            $btn.removeClass('layui-disabled');
        }

        var index = _findIndexOfWorkListByWorkId();
        if (index === -1 || window.workList.length === 1) {
            return;
        }

        var $buttons = _getPrevNextButtonWrapper().find('button');
        var $prev = $buttons.filter('[data-action="prev"]');
        var $next = $buttons.filter('[data-action="next"]');

        if (index === 0) {
            _enabledBtn($next);
        } else if (index >= window.workList.length -1) {
            _enabledBtn($prev);
        } else {
            _enabledBtn($buttons);
        }
    }

    /**
     * 初始化操作列表按钮状态
     */
    function initOperationListStatus () {
        var operateId = zmnUtils.getQueryString('operateId');
        $('#operator-panel .layui-btn[data-id="' + operateId + '"]').addClass('active');

        // 呼叫中心时隐藏此操作
        if (top.isCallCenter) {
            $('.work-operation-header .header-left').hide();
        }
    }

    /**
     * 跳转到页面
     * @param params
     * @param opConfigObj
     * @param url
     * @param title
     */
    function jumpToPage(params) {
        // 初始赋值
        let url =  params.url;
        let title =  params.dialogTitle;

        // 清除多余的请求参数
        delete params.url;
        delete params.dialogTitle;

        window.currentWork = params;
        window.location.href =  zmnUtils.serializeURL(url, params);

        // 更新弹窗 title
        updateLayerTitile(title);
    }

    /**
     * 打开确认对话框
     * @param params 请求参数
     * @param btnList 按钮列表
     * @param content 内容
     * @param yesCallBack 第一个按钮callback，默认为跳转到派单页面
     * @param btn2CallBack 第二个按钮callback，默认为跳转到改派列表
     */
    function openConfirmDialog(params, btnList, content, yesCallBack, btn2CallBack) {
        layer.open({
            title: '提示',
            btn: btnList,
            content: content,
            yes: function (index, layero) {

                if (typeof yesCallBack === "function") {
                    yesCallBack();
                } else {
                    // 跳转到派单页面
                    jumpToPage(params)
                }

                // 关闭对话框
                layer.close(index);
            },
            btn2: function (index, layero) {

                if (typeof btn2CallBack === "function") {
                    btn2CallBack();
                } else {

                    // 跳转到改派列表
                    layer.msg('正在跳转到改派列表。', {time: 1500}, function () {
                        let url = OMS_BASE_URL + "/work/redistribute/list.action";
                        let operateURL = zmnUtils.serializeURL(url, {
                            orderId: params.orderId
                        });
                        top.layui.index.openTabsPage(operateURL, '改派列表');
                        parent.layer.closeAll();
                    });

                }

                // 关闭对话框
                layer.close(index);
            }
        });
    }

    /**
     * 跳转至【派单】或【改派列表】页面
     * @param data 待改派的记录
     * @param params
     */
    function jumpToDistributeOrRedistributePage(data, params) {
        if (data.redistributeId) {

            // 如果【审核状态】不是【待审核或处理中】
            if (!(data.auditStatus == 1 || data.auditStatus == 5)) {
                openConfirmDialog(params, ['直接改派', '取消'], '正在向附近的工程师发起改派求助，目前还没有工程师领单，确定直接改派订单吗？', null, () => {
                })
                return;
            }

            // 待【工程师主管】或【员工】审核
            switch (data.auditType) {
                case 1: // 主管
                    openConfirmDialog(params, ['直接改派', '等待主管处理'], '存在需工程师审核的取消申请，确定直接取消订单吗？', null, () => {
                    })
                    break;
                case 2: // 员工
                    openConfirmDialog(params, ['直接改派', '前去处理'], '存在进行中的改派申请，确定直接改派订单吗？', null, null)
                    break;
                default:
                    layer.msg("未知的审核人类型");
                    break;
            }

        } else {
            // 否则，走原有逻辑
            jumpToPage(params)
        }
    }

    /**
     * 提示框
     * @param str {string} 提示内容;
     * @returns {*}
     */
    function toast(opt) {
        layer.msg(opt.title,{
            icon:opt.icon || (opt.success === true ? 1 : null),
            time:opt.time || 1000,
        },function () {
            if(opt.icon == 1 || opt.success === true){
                if(opt.cb && typeof(opt.cb) === 'function'){
                    opt.cb();
                }else{
                    goOperateHome();
                }
            }
        })
    }

    /**
     * 初始化页面事件
     */
    function initEvent () {
        $('.operator-panel').on('click', 'button', function (e) {
            var $button = $(this);
            var operateId = $(this).data('id');
            var params = zmnUtils.getQueryParams();
            var config = $.extend({}, params, { type: operateId });
            if (config.moduleId == undefined) {
                config.moduleId = defaultModuleId;
                params.moduleId = defaultModuleId;
            }
            operationUtils.getOpObj(config).done(function (opObj) {
                if (opObj && opObj.canOperate) {
                     var opConfigObj = operationUtils.getOpConfigById(operateId);
                     var url = opConfigObj ? opConfigObj.url : '';

                     // 特殊处理
                     if (opConfigObj && opConfigObj.special) {
                         if(opConfigObj.callback){
                             if (opConfigObj.id === 9) {
                                 opConfigObj.callback(params, function () {
                                     layer.msg('算账成功', {
                                         icon: 1,
                                         time: 1000
                                     }, function () {
                                         goOperateHome()
                                     })
                                 });
                             }else if (opConfigObj.id === 721){
                                 opConfigObj.callback(params, function (data) {
                                     if (data > 0) {
                                         layer.open({
                                             title: '提示',
                                             btn: ['前往查看', '继续添加'],
                                             content: '已添加过赔偿单，请确认是否继续添加',
                                             yes: function (index, layero) {
                                                 layer.closeAll();
                                                 // 跳转工单列表查询
                                                 parent.layer.closeAll();
                                                 if (params.moduleId == MODULE_ID_ZS) {
                                                     parent.layui.index.openTabsPage(OMS_BASE_URL + "/work/list.action?orderId=" + params.orderId + "&singleWorkType=" + 4, '工单管理');
                                                 }else if (params.moduleId == MODULE_ID_YEYX) {
                                                     parent.layui.index.openTabsPage(OMS_BASE_URL + "/ys/work/list.action?orderId=" + params.orderId + "&singleWorkType=" + 4, '工单管理');
                                                 }else if (params.moduleId == MODULE_ID_CNHB) {
                                                     parent.layui.index.openTabsPage(OMS_BASE_URL + "/cnhb/work/list.action?orderId=" + params.orderId + "&singleWorkType=" + 4, '工单管理');
                                                 }else if (params.moduleId == MODULE_ID_SAAS) {
                                                     parent.layui.index.openTabsPage(OMS_BASE_URL + "/saas/work/list.action?orderId=" + params.orderId + "&singleWorkType=" + 4, '工单管理');
                                                 }
                                             },
                                             btn2: function (index, layero) {
                                                 layer.close(index);
                                                 url = OMS_BASE_URL + '/work/modify/compensate.action';
                                                 params.operateId = operateId;
                                                 // 更新弹窗 title
                                                 updateLayerTitile('赔偿单');
                                                 // 跳转
                                                 window.location.href = zmnUtils.serializeURL(url, params);
                                             }
                                         });
                                     } else {
                                         url = OMS_BASE_URL + '/work/modify/compensate.action';
                                         params.operateId = operateId;
                                         // 更新弹窗 title
                                         updateLayerTitile('赔偿单');
                                         // 跳转
                                         window.location.href = zmnUtils.serializeURL(url, params);
                                     }
                                 });
                             }  else if (opConfigObj.id === 4) {
                                 opConfigObj.callback(params, function (data) {
                                     // 派单
                                     params.url = OMS_BASE_URL + "/work/modify/distribute.action"
                                     params.operateId = operateId;
                                     params.dialogTitle = '派单'
                                     jumpToDistributeOrRedistributePage(data, params)
                                 });
                             } else if (opConfigObj.id === 17) {
                                 opConfigObj.callback(params, function (data) {
                                     // 派单（新）
                                     params.url = OMS_BASE_URL + "/work/modify/distributeNew.action";
                                     params.operateId = operateId;
                                     params.dialogTitle = '派单（新）'
                                     jumpToDistributeOrRedistributePage(data, params)
                                 });
                             } else {
                                 opConfigObj.callback(params);
                             }
                             return;
                         }
                         switch (opConfigObj.id) {
                             case 502:
                             case 503: {
                                 var queryParams = {
                                     workId: params.workId,
                                     orderId: params.orderId
                                 };
                                 operationUtils.handler.complaintAndAbnormal(opConfigObj, params, function (text) {
                                     window.location.href = zmnUtils.serializeURL(opConfigObj.host + opConfigObj.listURL, queryParams);
                                 }, function (text) {
                                     let currentUrl =  zmnUtils.serializeURL(opConfigObj.host + opConfigObj.editURL, queryParams);
                                     if (text === '新增投诉'){
                                         operationUtils.openDialog({
                                             title: '新增投诉',
                                             content: currentUrl
                                         });
                                     } else {
                                         window.location.href = currentUrl;
                                     }
                                 });

                                 break;
                             }
                             default:
                                 break;
                         }

                         return;
                     }

                    var title = $button.text();
                    if (!url) {
                        layer.msg('操作暂不可用');
                        return;
                    } else if (!params) {
                        layer.msg('参数不全');
                        return;
                    }

                    // 更新弹窗 title
                    updateLayerTitile(title);

                    params['operateId'] = operateId;
                    // 跳转
                    window.location.href = zmnUtils.serializeURL(url, params);
                } else {
                    layer.msg(opObj.msg);
                }
            });
        });

        _getPrevNextButtonWrapper().on('click', 'button', function (e) {
            var $this = $(this);
            var action = $(this).data('action');
            var text = {
                prev: '到顶啦',
                next: '没有更多啦'
            };

            var index = _findIndexOfWorkListByWorkId();

            if (index === -1) {
                layer.msg('操作暂不可用');
                return;
            }

            if (index === 0 && action === 'prev') {
                layer.msg(text.prev);
                return;
            }

            if (index === workList.length - 1 && action === 'next') {
                layer.msg(text.next);
                return;
            }

            index = action === 'prev' ? --index : ++index;
            var workInfo = workList[index];

            if (!workInfo) {
                layer.msg('操作暂不可用');
                return;
            }

            window.setCurrentWork(workInfo);

            window.location.href = zmnUtils.serializeURL(config.url.homeURL, {
                operateId: 103,
                workId: workInfo.workId,
                orderId: workInfo.orderId,
                moduleId: zmnUtils.getQueryString('moduleId') || defaultModuleId
            });
        });
    }

    /**
     * 初始化工单页面
     */
    function initPage () {
        window.workId = zmnUtils.getQueryString('workId');

        initOperationListStatus();

        Pace.once('done', function () {
            initPrevNextButtonStatus();
        });
    }

    /**
     * 程序入口
     */
    function init () {
        initPage();
        initEvent();
    }

    // 初始化
    init();

    exports('list_modify_common', {
        goOperateHome: goOperateHome,
        toast: toast,
        goSomeWorkDetail: _goSomeOperateHome,
        accMul: accMul,
        accAdd: accAdd
    });
});
